package com.scs.application.modules.msg.handler;

import com.alibaba.fastjson.JSON;
import com.scs.application.modules.msg.entity.PushRecord;
import com.scs.application.modules.msg.enums.HandlerType;
import com.scs.application.modules.msg.model.EmailMessage;
import com.scs.application.modules.msg.model.InnerNoticeMessage;
import com.scs.application.modules.msg.model.Message;
import com.scs.application.modules.msg.model.SmsMessage;
import com.scs.application.modules.msg.service.PushRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 */
@Component
public class MessageSenderCompleteHandler extends MessageSenderHandler {

    @Autowired
    private PushRecordService pushRecordService;

    @Override
    public HandlerType getHandlerType() {
        return HandlerType.COMPLETE;
    }

    @Override
    public void handle(Message message, Exception e) {
        if(e != null){
            e.printStackTrace();
        }

        PushRecord pushRecord = new PushRecord();

        pushRecord.setMsgType(message.getMessageType().getCode());
        pushRecord.setTitle(message.getTitle());
        pushRecord.setContent(message.getContent());
        pushRecord.setTplKey(message.getTplKey());
        pushRecord.setIsSuccess(e == null ? 1 : 0);
        pushRecord.setExceptionContent(e != null ? e.getMessage() : null);

        if (message instanceof EmailMessage) {
            pushRecord.setReceiver(((EmailMessage) message).getTo());
        } else if (message instanceof SmsMessage) {
            pushRecord.setReceiver(((SmsMessage) message).getMobiles());
        }else if (message instanceof InnerNoticeMessage) {
            pushRecord.setReceiver(((InnerNoticeMessage) message).getReceiverCodes());
        }

        if (message.getTplDataMap() != null) {
            pushRecord.setTplParams(JSON.toJSONString(message.getTplDataMap()));
        }
        pushRecordService.save(pushRecord);
    }
}
